package com.example.library.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.library.common.Constants;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.example.library.common.Result;
import com.example.library.entity.Book;
import com.example.library.entity.User;
import com.example.library.entity.UserDTO;
import com.example.library.service.IUserService;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

import static com.example.library.common.Result.success;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 胡绍杆
 * @since 2022-06-16
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        System.out.println(user.getAccount());
        System.out.println("xxxxxxxxxxxxxxxxxxx");
        return userService.login(user);

    }

    @RequestMapping("/logout")
    public Result logout(){
        return userService.logout();
    }

//    @PostMapping("/register")
//    public Result register(@RequestBody User user){
//        String userid=user.getAccount();
//        String password=user.getPassword();
//        if (StrUtil.isBlank(userid) || StrUtil.isBlank(password)){
//            return Result.error(Constants.CODE_400,"参数错误");
//        }
//        return userService.register(user);
//    }

    @PostMapping("/changePwd")
    public Result changePwd(@RequestParam String account,
                            @RequestParam String password,
                            @RequestParam String newpassword
                            ){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("account",account);
        List<User> list = userService.list(queryWrapper);
        String oldPassword = list.get(0).getPassword();
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        boolean matches = encoder.matches(password, oldPassword);
        if (matches){
            UpdateWrapper<User> updateWrapper=new UpdateWrapper<>();
            String newPassword=encoder.encode(newpassword);
            updateWrapper.set("password",newPassword);
            return success(userService.update(updateWrapper));
        }
        return Result.error("500","原密码错误");

    }


    //用户分页显示
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam String account) {
        IPage<User> page=new Page<>(pageNum,pageSize);
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("account",account);
        return  success(userService.page(page,queryWrapper));
    }

    //导入
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        //List<Book> list = reader.readAll(Book.class);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<User> users = CollUtil.newArrayList();
        for (List<Object> row : list) {
            User user = new User();
            user.setAccount(row.get(0).toString());
            user.setPassword(row.get(1).toString());
            user.setSex(Integer.valueOf(row.get(2).toString()));
            user.setUsername(row.get(3).toString());
            user.setEmail(row.get(4).toString());
            user.setPhoto(row.get(5).toString());
            user.setRole(Integer.valueOf(row.get(6).toString()));
            user.setCash(Double.valueOf(row.get(7).toString()));
            user.setUserState(Integer.valueOf(row.get(8).toString()));
            users.add(user);
        }
        userService.saveBatch(users);
        return success(true);
    }

    //批量注销
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<String> ids) { // [1,2,3]
        System.out.println(ids);
        UpdateWrapper<User> updateWrapper=new UpdateWrapper<>();
        updateWrapper.in("account",ids);
        updateWrapper.eq("user_state",1);
        updateWrapper.set("user_state",0);
        if(userService.update(updateWrapper)){
            return Result.success();
        }
        return Result.error();
    }

    /**
     * yang
     * 所剩金额
     */
    @GetMapping("/getJine")
    public Result getJine(@RequestParam String account){
        User user = userService.getOne(new QueryWrapper<User>().eq("account",account));
        return Result.success(user.getCash());
    }
}
